package com.example.streamsqlpark.base.util;

import com.example.streamsqlpark.common.util.DateUtils;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.module.scala.DefaultScalaModule;

import java.text.SimpleDateFormat;

/**
 * @author voloiono
 * @date 2024/4/17 10:23
 */
public class JacksonUtil {
    private JacksonUtil() {
    }

    private static final ObjectMapper MAPPER;

    static {
        MAPPER = new ObjectMapper();
        MAPPER.registerModule(new DefaultScalaModule());
        MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,false);
        MAPPER.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS,false);
        MAPPER.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,false);
        MAPPER.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        MAPPER.setDateFormat(new SimpleDateFormat(DateUtils.fullFormat()));
    }

    public static <T> T read(String json,Class<T> clazz) throws JsonProcessingException {
        return MAPPER.readValue(json,clazz);
    }

    public static <T> T read(String json, TypeReference<T> typeReference)
            throws JsonProcessingException {
        return MAPPER.readValue(json, typeReference);
    }

    public static String write(Object object) throws JsonProcessingException {
        return MAPPER.writeValueAsString(object);
    }
}
